import { useKeyPress } from 'ahooks'
import { useDispatch } from 'react-redux'
import {
  removeSelectedComponent,
  copySelectedComponent,
  pasteComponent,
  moveComponent,
} from '@/store/modules/componentsReducer'
import useGetComponentInfo from './useGetComponentInfo'
import { ActionCreators } from 'redux-undo'

const isActiveElementValid = () => {
  const { activeElement } = document
  if (activeElement === document.body) return true
  if (activeElement?.matches('div[role="button"]')) return true
  return false
}

const useBindCanvasKeyPress = () => {
  const dispatch = useDispatch()
  const { selectedIndex } = useGetComponentInfo()

  useKeyPress(['backspace', 'delete'], () => {
    if (!isActiveElementValid()) return
    dispatch(removeSelectedComponent())
  })

  useKeyPress(['ctrl.c', 'meta.c'], () => {
    if (!isActiveElementValid()) return
    dispatch(copySelectedComponent())
  })

  useKeyPress(['ctrl.v', 'meta.v'], () => {
    if (!isActiveElementValid()) return
    dispatch(pasteComponent())
  })

  useKeyPress('uparrow', () => {
    dispatch(moveComponent({ oldIndex: selectedIndex, newIndex: selectedIndex - 1 }))
  })

  useKeyPress('downarrow', () => {
    dispatch(moveComponent({ oldIndex: selectedIndex, newIndex: selectedIndex + 1 }))
  })

  useKeyPress(
    ['ctrl.z', 'meta.z'],
    () => {
      dispatch(ActionCreators.undo())
    },
    {
      exactMatch: true,
    }
  )

  useKeyPress(
    ['ctrl.shift.z', 'meta.shift.z'],
    () => {
      dispatch(ActionCreators.redo())
    },
    {
      exactMatch: true,
    }
  )
}

export default useBindCanvasKeyPress
